﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sio.Mdm.Entities;
using Sio.Mdm.Types.Database;
using System.Reflection;

namespace Sio.Mdm.Security
{
    public static class SecurityTokenCache
    {
        static EntityCollection<VarnostniZeton> Tokens = new EntityCollection<VarnostniZeton>();
        static Dictionary<string, VarnostniZeton> Cache = new Dictionary<string, VarnostniZeton>();

        public static bool HasToken(string name)
        {
            if (Cache.ContainsKey(name))
            {
                return true;
            }

            VarnostniZeton token = EntityFactory.CreateInstance<VarnostniZeton>();

            if (token.Load<VarnostniZeton>(from r in new Filter<VarnostniZeton>()
                                           where r.Naziv == name
                                           select r
            ))
            {
                if (token.EntityState == EntityState.Unchanged)
                {
                    Cache.Add(name, token);
                    return true;
                }
            }

            return false;
        }

        public static bool AddToken(string name)
        {
            if (Config.IsIgnored(name) || HasToken(name))
            {
                return true;
            }

            VarnostniZeton token = EntityFactory.CreateInstance<VarnostniZeton>();

            token.Naziv = name;

            if (token.Update())
            {
                Cache.Add(name, token);
                return true;
            }

            return false;
        }

        static Type EntityType = typeof(IEntity);
        static Type CollectionType = typeof(IEntityCollection).MakeByRefType();

        public static Type ExtractTokenType(System.Reflection.MethodInfo method)
        {
            foreach (ParameterInfo param in method.GetParameters())
            {
				if (CollectionType.IsAssignableFrom(param.ParameterType))
                {
                    return param.ParameterType.GetGenericArguments()[0];
                }
				
                if (EntityType.IsAssignableFrom(param.ParameterType))
                {
                    return param.ParameterType;
                }
            }

            return null;
        }
    }
}
